package edu.seu.mart.controller;

import com.alibaba.fastjson.JSON;
import edu.seu.mart.entity.Pager;
import edu.seu.mart.model.MartException;
import edu.seu.mart.model.User;
import edu.seu.mart.service.ICartService;
import edu.seu.mart.service.IOrderItemService;
import edu.seu.mart.service.IOrderService;
import edu.seu.mart.service.IUserService;
import edu.seu.mart.utils.SecurityUtil;
import edu.seu.mart.web.Captcha;
import edu.seu.mart.web.SessionContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by samsung on 2015/3/6.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;
    @Resource
    private IOrderService orderService;
    @Resource
    private ICartService cartService;
    @Resource
    private IOrderItemService orderItemService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "user/login";
    }

    @RequestMapping("/login")
    public String login(String username, String checkcode, String password, Model model, HttpSession session) {
        String cc = (String) session.getAttribute("cc");
        if (!cc.equals(checkcode)) {
            model.addAttribute("error", "×");
            return "user/login";
        }
        User loginUser = userService.login(username, password);
        session.setAttribute("loginUser", loginUser);
        session.setAttribute("CartCount",cartService.getCount(loginUser.getId()));
        session.removeAttribute("cc");
        SessionContext.addSessoin(session);
        return "redirect:/goods/index";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "user/register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(String username, String email, String pw1, String pw2) {
        System.out.println(pw1 + pw2);
        if (userService.findUser(username).getTotal() == 0) {
            if (userService.findUserByEmail(email) == null) {
                if (pw1.equals(pw2)) {
                    try {
                        User user = new User();
                        user.setUsername(username);
                        user.setEmail(email);
                        user.setPassword(SecurityUtil.md5(username, pw1));
                        user.setStatus(1);
                        userService.save(user);
                    } catch (Exception e) {
                        throw new MartException("保存失败");
                    }
                } else {
                    throw new MartException("两次输入密码不一致");
                }
            } else {
                throw new MartException("邮箱已存在");
            }
        } else {
            throw new MartException("用户名已存在");
        }
        return "user/register";
    }

    @RequestMapping(value = "/check/{username}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    Details checkUser(@PathVariable String username) {

        Details userDetails = new Details();
        Pager<User> pager = userService.findUser(username);
        if (pager.getTotal() == 0) {
            userDetails.isUnique = true;
        } else {
            userDetails.isUnique = false;
        }
        return userDetails;
    }
    class Details {
        public boolean isUnique = false;
    }

    @RequestMapping("/drawCheckCode")
    public void drawCheckCode(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setContentType("image/jpg");
        int width = 200;
        int height = 30;
        Captcha c = Captcha.getInstance();
        c.set(width, height);
        String checkcode = c.generateCheckcode();
        session.setAttribute("cc", checkcode);
        OutputStream os = resp.getOutputStream();
        ImageIO.write(c.generateCheckImg(checkcode), "jpg", os);
    }
    @RequestMapping(value="/active", method = RequestMethod.POST)
    public void active(HttpServletResponse response,@RequestParam String str,HttpSession session) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        User user1= (User) session.getAttribute("loginUser");
        User user=userService.load(user1.getId());
        if(str.equals("未中奖")){
            response.getWriter().write("很遗憾，您未中奖");
        }
        if(str.equals("免单10元")){
            user.setMoney(user.getMoney()+10);
            response.getWriter().write("您的10元奖金已存入您的账户，请查收！");
        }
        if(str.equals("免单5元")){
            user.setMoney(user.getMoney()+5);
            response.getWriter().write("您的5元奖金已存入您的账户，请查收！");
        }
        if(str.equals("免单50元")){
            user.setMoney(user.getMoney()+50);
            response.getWriter().write("您的50元奖金已存入您的账户，请查收！");
        }
        user.setTimes(user.getTimes()-1);
        userService.update(user);
        session.setAttribute("loginUser",user);

    }

    @RequestMapping(value="/getTimes", method = RequestMethod.POST)
    public void getTimes(HttpServletResponse response,HttpSession session) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        User user1= (User) session.getAttribute("loginUser");
        User user=userService.load(user1.getId());
        if(user.getTimes()>0){
            response.getWriter().write("1");

        }else {
            response.getWriter().write("0");

        }

    }
    @RequestMapping(value = "/chat", method = RequestMethod.GET)
    public String chat() {
        return "chat";
    }

    @RequestMapping(value="/testIndex")
    public String index() {

        return "user/test";
    }
    @RequestMapping(value="/test",produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody List<Test> test(HttpServletResponse response) throws IOException {
        List<Test> testList=new ArrayList<Test>(){};
        Test test=new Test();
        test.name="1";
        for(int i=1;i<10;i++) {
            test.numList.add(i);
        }
        Test test1=new Test();
        test1.name="2";
        for(int i=1;i<10;i++) {
            test1.numList.add(i);
        }
        testList.add(test);
        testList.add(test1);

//        response.getWriter().write(testList.toString());
        return  testList;

    }
    class Test {
        public String name ;
        public List<Integer> numList=new ArrayList<Integer>(){};
    }
    /**
     * 订单管理
     */

}
